Kenneth Leroy Busbee and Dave Braunschweig
OverviewIndex notation is used to specify the elements of an array.[1] Most current programming languages use聽square brackets [] as the array index operator. Older programming languages, such as FORTRAN, COBOL, and BASIC, often use parentheses ()聽as the array index operator.
DiscussionExample:
LanguageExampleC++int ages[] = {49, 48, 26, 19, 16};int myAge = ages[2];C#int[] ages = {49, 48, 26, 19, 16};int myAge = ages[2];Javaint[] ages = {49, 48, 26, 19, 16};int myAge = ages[2];JavaScriptvar ages = [49, 48, 26, 19, 16];int myAge = ages[2];Pythonages = [49, 48, 26, 19, 16]my_age = ages[2]Swiftvar ages:[Int] = [49, 48, 26, 19, 16]var my_age = ages[2]As an operator, square brackets either provide the value held by the member of the array (Rvalue) or change the value of member (Lvalue). In the above example, the member that is two offsets from the front of the array (the value 26) is assigned to the variable named myAge. The dereference operator of [2] means to go the 2nd聽offset聽from the front of the ages array and get the value stored there. In this case, the value would be 26. In most current programming languages, the array members (or elements) are referenced starting at zero. The more common way for people to reference a list is by starting with position one. Consider:
PositionIndexMiss AmericaOther Contestszero offsets from the frontages[0]Winner1st聽Placeone offset from the frontages[1]1st聽Runner Up2nd聽Placetwo offsets from the frontages[2]2nd聽Runner Up3rd聽Placethree offsets from the frontages[3]3rd聽Runner Up4th聽Placefour offsets from the frontages[4]4th聽Runner Up5th聽PlaceSaying that my cousin is the 2nd聽Runner-Up in the Miss America contest sounds so much better than saying that she was in 3rd聽Place. We would be talking about the same position in the array of the five finalists.
ages[3] = 20;
This is an example of changing an array鈥檚 value by assigning 20 to the 4th聽member of the array and replacing the value 19 with 20. This is an Lvalue context because the array is on the left side of the assignment operator.
Key Termsarray memberAn element or value in an array.indexAn operator that allows us to reference a member of an array.offsetThe method of referencing array members by starting at zero.Referencescnx.org: Programming Fundamentals – A Modular Structured Approach using C++Wikipedia: Index notation ↵